<template>
  <!-- 添加和修改课时表单 -->
  <el-dialog :visible.sync="dialogVideoFormVisible" title="添加课时">
    <el-form :model="video" label-width="120px">
      <el-form-item label="课时标题">
        <el-input v-model="video.title" />
      </el-form-item>
      <el-form-item label="课时排序">
        <el-input-number
          v-model="video.sort"
          :min="0"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="是否免费">
        <el-radio-group v-model="video.free">
          <el-radio :label="true">免费</el-radio>
          <el-radio :label="false">默认</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="上传视频">
        <!-- TODO -->
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close()">取 消</el-button>
      <el-button
        :disabled="saveVideoBtnDisabled"
        type="primary"
        @click="saveOrUpdateVideo"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import videoApi from "@/api/edu/video";
export default {
  data() {
    return {
      dialogVideoFormVisible: false, // 弹出框默认给关闭
      video: {
        // 小节（课时）
        sort: 0,
        free: false,
      },
      saveVideoBtnDisabled: false, // 避免重复提交
    };
  },

  methods: {
    // chapter保存的时候是不是需要courseId video保存的时候需要courseId、chapterId
    saveOrUpdateVideo() {
      if (this.video.id) {
        this.update();
      } else {
        this.save();
      }
    },
    // 添加课时
    save() {
      // 1.要有courseId 2.chapterId
      this.video.courseId = this.$parent.$parent.courseId;
      videoApi.addVideo(this.video).then((response) => {
        this.$message.success("添加成功");
        this.help();
      });
    },
    // 修改课时
    update() {
      videoApi.updateVideoById(this.video).then((response) => {
        this.$message.success("修改成功");
        this.help();
      });
    },
    // 根据课时id获取课时信息，用于回显
    getVideoById(id) {
      videoApi.getVideoById(id).then((response) => {
        this.video = response.data.item;
      });
    },

    open(chapterId, videoId) {
      if (videoId) {
        // 回显
        this.getVideoById(videoId);
      } else {
        // 新增的时候给chapterId赋值
        this.video.chapterId = chapterId;
      }
      this.dialogVideoFormVisible = true;
    },
    close() {
      this.dialogVideoFormVisible = false;
      this.video = {
        sort: 0,
        free: false,
      };
    },
    help() {
      // 1.刷新页面
      this.$parent.nestedListChapter(this.video.courseId);
      // 1.关闭弹窗,充值表单数据
      this.close();
    },
  },
};
</script>